<?php

// use JohnLui\AliyunOSS\AliyunOSS;

require_once base_path() .'/vendor/johnlui/aliyun-oss/oss/aliyun.php';

use Aliyun\OSS\OSSClient;
use \Aliyun\OSS\Models\OSSOptions;

class Images{
	public static $imageRules = array(
			'file' => 'mimes:jpeg,bmp,png|max:5000|min:1'
	);
	
	
// 	public static function storeBannerImage($file){
// 		return static::store($file,'banner/');
// 	}
	
	public static function storeImage($file,$oldKey = null){
		
		$key = Images::buildKey($file);
		$key = Images::storeFile($file, $key);
		if (!empty($oldKey)){
			Images::delete($oldKey);
		}
		return $key;
	}
	
	public static function storeVedio($file,$suffix,$key = null){
		if (empty($key)){
			$key = Images::buildKey($file, $suffix);
		}
		return Images::storeFile($file, $key,"vedio/");
	}
	
	private static function buildKey($file,$suffix=""){
		if ($file instanceof UploadedFile) {
			$key = md5($file->getRealPath().str_random(8));
		} else {
			$key = md5($file.str_random(8));
		}
		return $key.$suffix;
	}
	private static function storeFile($file,$key,$prefix=""){
		$path = null;
		if ($file instanceof UploadedFile) {
			$path = $file->getRealPath();
		} else {
			$path = $file;
		}
		
		return OSS::put($prefix.$key, $path);
	}
	
	/*
	public static function storeProductImage($file,$productId){
		return static::store($file,$productId.'/');
	}
	public static function store($file,$path = ''){
		$validation = Validator::make(array("file" => $file), static::$imageRules);
		if (! $validation->fails()) {
		
			// If validation pass, get filename and extension
			// Generate random (12 characters) string
			// And specify a folder name of uploaded image
			$originName      = $file->getClientOriginalName();
			$extension       = $file->getClientOriginalExtension();
			$fileName        = $path.md5($originName.str_random(8)).'.'.$extension;
			$base 			 = Config::get("mao.image_base");
			//$destinationPath = $base.$fileName;
		
			// Move file to generated folder
			$file->move($base.$path, $fileName);
		
			// Crop image (possible by Intervention Image Class)
			// And save as miniature
			//Image::make($destinationPath . '/' . $fileName)->crop(250, 250, 10, 10)->save($destinationPath . '/min_' . $fileName);
		
			// Insert image information to database
			return array('image' => $fileName,'success'=> true);
		} else {
			$messages = $validation->messages();
			$error = "";
			if ($messages->has('mimes')){
				$error = "不是合法的图片文件";
			} else  if ($messages->has('max')){
				$error = "图片不能超过500KB";
			} else{
				$error = "图片没有内容";
			}
			return array('success'=>false,'error'=> $error);
		}
	}*/
	
	public static function delete($key){
		/*
		$base = Config::get("mao.image_base");
		$path = $base.$path;
		if (File::exists($path)){
			File::delete($path);
			return true;
		}*/
		OSS::delete($key);
		return true;
	}
	public static function deleteDirectory($path){
		$base = Config::get("mao.image_base");
		$path = $base.$path;
		File::deleteDirectory($path);
	}
	
	public static function response($data){
// 		$path,$w = 0,$h = 0
		$path = array_get($data, 'image');
		$w = array_get($data, 'w',0);
		$h = array_get($data, 'h',0);
		$base = Config::get("mao.image_base");
		$path = $base.$path;
		$img = Image::make($path);
		//$rw = $img->width();
		//$rh = $img->height();
		
		//压缩，并且根据宽高中心截取
		if ($w != 0 && $h != 0){
			$img = $img->fit($w,$h);
			/*
			$wrate = $w / $rw;
			$hrate = $h / $rh;
			
			$rate = $rate = $wrate > $hrate ? $wrate : $hrate;
// 			if ($wrate > 1 ||  $hrate > 1){
// 				//宽和高度存在放大，则需要按最大比例放大，
				
// 			} else{
// 				//缩小，则需要按照小比例缩小
// 				$rate = $wrate > $hrate ? $hrate : $wrate;
// 			}
			//1.先按照短边压缩
			$nw = ceil($rw * $rate);
			$nh = ceil($rh * $rate);
			$img = $img->resize($nw,$nh);
			//2.截取
			$x = ($nw - $w) / 2;
			$y = ($nh - $h) / 2;
			$img = $img->crop($w,$h,floor($x),floor($y));*/
			//
			
		} else if ($w != 0 && $h == 0){
			//更具宽度进行压缩
// 			$rate = $rw / $w;
			$img = $img->widen($w);
			//$img = $img->resize($rw * $rate,$rh * $rate);
		} else if ($w == 0 && $h != 0){
			//根据高度压缩
			//$rate = $rh / $h;
			//$img = $img->resize($rw * $rate,$rh * $rate);
			$img = $img->heighten($h);
		}
		return $img->response();
	}
	
	public static function url($path,$w = 0,$h = 0){
		/**
		$param = array("image" => $path);
		if ($w != 0){
			$param['w'] = $w;
		}
		if ($h != 0){
			$param['h'] = $h;
		}
		return URL::route('image',$param);*/
		if ($w != 0 && $h != 0){
			$path = $path."@".$w."w_".$h."h_1c_1e";
		} else if ($w != 0){
			$path = $path."@".$w."w";
		} else if ($h != 0){
			$path = $path."@".$h."h";
		}
		$url = Config::get('mao.image_domain').$path;
		return $url;
	}
	
	public static function test(){
		return "test";
	}
}


class OSS {
	public static function boot(){
		
		
// 		$oss = new MOSS(Config::get('mao.oss.servr-internal'),Config::get('mao.oss.key'),Config::get('mao.oss.secret'));
// 		$oss->setBucket(Config::get("mao.oss.bucket"));
		
// 		$oss = AliyunOSS::boot(Config::get('mao.oss.server'),Config::get('mao.oss.key'),Config::get('mao.oss.secret'));
// 		$oss->setBucket(Config::get("mao.oss.bucket"));
		
		$oss = OSSClient::factory([
				OSSOptions::ENDPOINT => Config::get('mao.oss.server'),
				'AccessKeyId' => Config::get('mao.oss.key'),
				'AccessKeySecret' => Config::get('mao.oss.secret')
		]);
// 		Log::info("oss info =>" . serialize($oss));
		return $oss;
	}
	

	public static function put($key, $filePath)
	{
		$key = Config::get('mao.oss.base').$key;
// 		$putObjectResult = OSS::boot()->uploadFile($key,$filePath);
		$client = OSS::boot();
		$putObjectResult = $client->putObject(array(
				'Bucket' => Config::get("mao.oss.bucket"),
				'Key' => $key,
				'Content' => fopen($filePath, 'r'),
				'ContentLength' => filesize($filePath)
		));
		return $key;
	}

	public static function delete($key){
// 		return OSS::boot()->deleteFile($key);
		$client = OSS::boot();
		return $client->deleteObject(array(
				'Bucket' => Config::get("mao.oss.bucket"),
				'Key' => $key
		));
// 		return OSS::boot()->deleteObject($key);

	}
	
// 	/**
// 	 * 删除一个Object
// 	 *
// 	 * @param array $options 可以包含以下Key:
// 	 * <li>Bucket(string, 必选) - 要删除的Object所在的Bucket</li>
// 	 * <li>Key(string, 必选) - 要删除的Object的Key</li>
// 	 *
// 	 * @return void
// 	 */
// 	public function deleteObject(array $options) {
// 		return $this->execute(__FUNCTION__, $options);
// 	}
	
	
	/*
	public static function url($ossKey)
	{
		return MOSS::boot()->getUrl($ossKey,new \DateTime("+1 day"));
	}*/

	/*
	public static function createBucket($bucketName)
	{
		return OSSWrapper::boot()->createBucket($bucketName);
	}

	public static function getAllObjectKey($bucketName)
	{
		return OSSWrapper::boot()->getAllObjectKey($bucketName);
	}*/

}